package com.lct.simpleforecast

import android.app.Application
import android.content.Context
import android.content.pm.ApplicationInfo
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Looper
import com.lct.simpleforecast.delegates.DelegatesExt
import com.lct.simpleforecast.extensions.logE
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.squareup.leakcanary.LeakCanary
import com.squareup.leakcanary.RefWatcher
import com.wanjian.cockroach.Cockroach
import com.wanjian.cockroach.ExceptionHandler
import org.jetbrains.anko.onUiThread
import org.jetbrains.anko.toast

/**
 * Author：SkySmile
 * Date：2018/7/4
 * Description：application
 */
class MyApplication : Application() {
    companion object {
        var instance: MyApplication by DelegatesExt.notNullSingleValue()
        var refWatcher: RefWatcher by DelegatesExt.notNullSingleValue()
        val isDebug: Boolean by lazy { instance.isAppInDebug() }
    }

    init {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white)
            ClassicsHeader(context)
        }
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
            ClassicsFooter(context).setDrawableSize(20f)
        }
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        refWatcher = installLeakCanary()
        if (!isDebug) {
            installCockroach()
        }
    }

    /**
     * 安装LeakCanary
     * 如果当前的进程是用来给LeakCanary 进行堆分析的则return，
     * 否则执行LeakCanary的install方法
     *
     * @return RefWatcher
     */
    private fun installLeakCanary(): RefWatcher {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return RefWatcher.DISABLED
        }
        return LeakCanary.install(this)
    }

    /**
     * 判断是否是debug模式
     */
    private fun isAppInDebug() = (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0

    /**
     * 装载Cockroach
     */
    private fun installCockroach() {
        Cockroach.install(object : ExceptionHandler() {
            override fun onUncaughtExceptionHappened(p0: Thread?, p1: Throwable?) {
                val errorMsg = "--->onUncaughtExceptionHappened:$p0\n${p1?.message}"
                errorMsg.logE("AndroidRuntime")
                onUiThread { toast("发生异常，请查看日志") }
            }

            override fun onBandageExceptionHappened(p0: Throwable?) {

            }

            override fun onEnterSafeMode() {

            }

            override fun onMayBeBlackScreen(e: Throwable?) {
                super.onMayBeBlackScreen(e)
                val thread = Looper.getMainLooper().thread
                val errorMsg = "--->onUncaughtExceptionHappened:$thread\n$e"
                errorMsg.logE("AndroidRuntime")
                Thread.getDefaultUncaughtExceptionHandler()
                        .uncaughtException(thread, RuntimeException("black screen"))
            }
        })
    }

    /**
     * 判断网络是否可用
     */
    fun isNetworkAvailable(): Boolean {
        val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo: NetworkInfo? = manager.activeNetworkInfo
        return networkInfo?.isAvailable ?: false
    }
}